package org.lanqiao.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.lanqiao.util.BeanToJsonWriter;
import org.lanqiao.util.SqlUtil;
import org.lanqiao.vo.JsonResultVo;

import com.google.gson.Gson;

/**
 * 管理员登录
 * @author Songzt@lanqiao.org
 *
 */
@WebServlet("/adminLogin")
public class AdminLoginServlet extends HttpServlet {

	 	@Override
	 	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 			
			request.setCharacterEncoding("utf-8");
			String username =request.getParameter("username");
			String password =request.getParameter("password");
			String sql="select * from  admin where username=? and password =?";
			
			JsonResultVo<String>  jsonResult =new JsonResultVo<String>();
			try{
					List<HashMap<String,Object>>   list =SqlUtil.executeQuery(sql, username,password);
					if(list.size()>0){
						//获取回话Session对象，用来存储已经登录的用户名信息
						HttpSession  session  =request.getSession();
						//谨记此Key，可用来判定用户是否登录,同时和前端的Sesison或者Cookie保持一致，且返回到前端
						session.setAttribute("loginAdminKey", username);
						jsonResult.setCode("200"); //2oo表示成功
						jsonResult.setInfo("登录成功");
						jsonResult.setData(username);
					}else{
						jsonResult.setCode( "404"); //404表示用户没有找到
						jsonResult.setInfo( "用户名或者密码错误");
					}
			}catch(Exception ex){
				jsonResult.setCode( "500"); 
				jsonResult.setInfo( "连接数据库异常");
			
			}
			BeanToJsonWriter.write(response, jsonResult);
			
			
		}
}
